<template>
    <div class="content declare-list-content">
        <div class="content-top">
            <Button
                class="icon-btn"
                type="primary"
                @click="addDeclaration"
            >
                <i class="iconfont icon-shanchu"></i> 新建报关单
            </Button>
            <Button
                class="icon-btn"
                @click="batchDownload"
                type="default"
            >
                <i class="iconfont icon-tianjiashangpin"></i> 批量下载随附单据
            </Button>
            <Button
                class="icon-btn"
                type="default"
                @click="sendDeclare"
            >
                <i class="iconfont icon-xiugaishangpin"></i> 批量导入单一窗口
            </Button>
            <Button class="icon-btn" @click="importModel" type="primary">
                <i class="iconfont icon-shanchu"></i> 导入
            </Button>
            <Button type="primary" @click="reportExport">报表导出</Button>
            <Button type="primary" :disabled="disFix" @click="handleFix">修改</Button>
            <Button type="primary" :disabled="disFix" @click="handleBack">撤销</Button>
            <SearchExpand class="search-collapse-small">
                <Form class="clearfix">
                    <Row>
                        <iCol span="2">
                            <div class="search-label">内部编号</div>
                        </iCol>
                        <iCol span="4">
                            <Input
                                v-model="searchData.declareNo"
                                type="text"
                                placeholder="请输入内部编号"
                            ></Input>
                        </iCol>
                        <iCol span="2">
                            <div class="search-label">订单编号</div>
                        </iCol>
                        <iCol span="4">
                            <Input
                                v-model="searchData.businessNo"
                                type="text"
                                placeholder="请输入订单编号"
                            ></Input>
                        </iCol>

                        <iCol span="2">
                            <div class="search-label">通关状态</div>
                        </iCol>
                        <iCol span="4">
                            <Select
                                v-model="searchData.businessStatus"
                                clearable
                            >
                                <Option
                                    v-for="item in businessStatusArr"
                                    :value="item.value"
                                    :key="item.value"
                                >{{ item.label }}</Option>
                            </Select>
                        </iCol>

                        <iCol span="2">
                            <div class="search-label">企业内部编码</div>
                        </iCol>
                        <iCol span="4">
                            <Input
                                v-model="searchData.etpsInnerInvtNo"
                                type="text"
                                placeholder="请输入企业内部编码"
                            ></Input>
                        </iCol>
                        <iCol span="2">
                            <div class="search-label">收发货人</div>
                        </iCol>
                        <iCol span="4">
                            <Input
                                v-model="searchData.tradeName"
                                type="text"
                                placeholder="请输入收发货人名称"
                            ></Input>
                        </iCol>

                        <iCol :span="2">
                            <div class="search-label">申报日期</div>
                        </iCol>
                        <iCol :span="4">
                            <DatePicker
                                style="width:100%;"
                                type="daterange"
                                placeholder="请选择创建时间"
                                @on-change="handleSearchDateChange"
                                placement="bottom"
                            />
                        </iCol>
                        <iCol span="2">
                            <div class="search-label">柜号</div>
                        </iCol>
                        <iCol span="4">
                            <Input
                                v-model="searchData.containerNo"
                                type="text"
                                placeholder="请输入柜号"
                            ></Input>
                        </iCol>
                        <iCol span="2">
                            <div class="search-label">提运单号</div>
                        </iCol>
                        <iCol span="4">
                            <Input
                                v-model="searchData.billNo"
                                type="text"
                                placeholder="请输入提运单号"
                            ></Input>
                        </iCol>
                        <iCol span="2" style="text-align:right;"></iCol>
                        <iCol span="2" style="text-align:left;">
                            <Button
                                @click="getList"
                                type="primary"
                            >查询</Button>
                        </iCol>
                    </Row>
                </Form>
            </SearchExpand>
        </div>
        <DeclareTable
            :data="dataList"
            :editDisabled="!canEdit"
            :viewDisabled="!canView"
            @editEvent="handleEdit"
            @viewEvent="handleView"
            @moreEvent="openMoreModal"
            @selection-change="handleSelectionChange"
        ></DeclareTable>
        <Pagination
            :pageSize.sync="searchData.pageSize"
            :current.sync="searchData.pageNum"
            :total="searchData.total"
            @change="queryDeclareList"
        />
        <Modal
            class-name="no-border"
            v-model="delDataModel"
            width="390"
            title="Common Modal dialog box title"
            :closable="false"
        >
            <div slot="header">
                {{ delModalObj.title }}
                <Icon class="f-fr" type="ios-close" @click="delCancel" />
            </div>
            <div class="clearfix">
                <div class="f-fl icon">
                    <Icon type="ios-alert" />
                </div>
                <div class="f-fl modal-content">{{ delModalObj.dic }}</div>
            </div>
            <div slot="footer">
                <Button type="default" @click="delCancel">取消</Button>
                <Button
                    type="primary"
                    @click="delOk(currentDeclareId)"
                >确定</Button>
            </div>
        </Modal>
        <Modal v-model="makeFileModal" :closable="false">
            <div slot="header">
                制作文件
                <Icon class="f-fr" type="ios-close" @click="makeFileCancel" />
            </div>
            <p style="font-size:14px;color:#383A4A;margin-bottom:8px;">
                <span style="color:#F45050">*</span>选择文件类型
            </p>
            <CheckboxGroup v-model="makeFileObj.types">
                <Checkbox label="NORMAL_DECLARE">
                    <span>报关单</span>
                </Checkbox>
                <Checkbox label="CONTRACT">
                    <span>合同</span>
                </Checkbox>
                <Checkbox label="INVOICE">
                    <span>发票</span>
                </Checkbox>
                <Checkbox label="PACKING_lIST">
                    <span>装箱单</span>
                </Checkbox>
            </CheckboxGroup>
            <p
                style="font-size:14px;color:#383A4A;margin-top:18px;margin-bottom:8px;"
            >
                是否加盖电子签章
            </p>
            <p style="margin-bottom:20px;">
                <RadioGroup v-model="makeFileObj.isCachet">
                    <Radio label="1">
                        <span>盖章</span>
                    </Radio>
                    <Radio label="0">
                        <span>不盖章</span>
                    </Radio>
                </RadioGroup>
            </p>
            <Progress :percent="makeFilePercent" :class="{ hide: isHide }" />
            <div slot="footer">
                <Button type="default" @click="makeFileCancel">取消</Button>
                <Button type="primary" @click="makeFileOk">开始制作</Button>
            </div>
        </Modal>
        <!-- 操作记录 -->
        <div v-if="operationRecordModal">
            <Modal
                v-model="operationRecordModal"
                width="746"
                :closable="false"
                :mask-closable="false"
            >
                <div slot="header">
                    报文记录
                    <Icon
                        class="f-fr"
                        type="ios-close"
                        @click="operationRecordCancel"
                    />
                </div>
                <Table
                    :columns="operationRecordListColumns"
                    :data="operationRecordList"
                ></Table>
                <div slot="footer">
                    <Button
                        type="default"
                        @click="operationRecordCancel"
                    >取消</Button>
                </div>
                <Pagination
                    :pageSize.sync="receiptData.pageSize"
                    :current.sync="receiptData.pageNum"
                    :total="receiptTotal"
                    @change="getReceiptInfo"
                />
            </Modal>
        </div>

        <!--申报失败-->
        <Modal
            v-model="declareResultModal"
            width="746"
            class="col-2"
            :closable="false"
        >
            <div slot="header">
                申报失败
                <Icon class="f-fr" type="ios-close" @click="cancelDeclare" />
            </div>
            <Table
                :columns="declareResultDataColumns"
                :data="declareResultDataList"
            ></Table>
            <div slot="footer" style="display:none">
                <Button
                    type="default"
                    @click="declareResultModal = false"
                >取消</Button>
                <Button type="primary">重新导入</Button>
            </div>
        </Modal>

        <div v-if="modalParams.declareFailureShow">
            <declareFailure
                v-model="modalParams.declareFailureShow"
                :declareFailure="modalParams.declareFailureParams"
            />
        </div>

        <div v-if="modalParams.declareSucShow">
            <declareSuccessModal
                v-model="modalParams.declareSucShow"
                :declareSuccess="modalParams.declareSucParams"
            />
        </div>

        <!-- 导入数据 -->
        <batchDownloadFailModal ref="batchDownloadFailModalRef" />
        <printFile ref="printFileRef"></printFile>

        <div class="more-box" @click="handleMore">
            <ul>
                <li>
                    <a href="javascript:;">导入单一窗口</a>
                </li>
                <li>
                    <a href="javascript:;">删除</a>
                </li>
                <li>
                    <a href="javascript:;">制作文件</a>
                </li>
                <li>
                    <a href="javascript:;">打印文件</a>
                </li>
                <li>
                    <a href="javascript:;">报文记录</a>
                </li>
            </ul>
        </div>
        <importModal @importSuccess="getList" ref="importModalRef" />
    </div>
</template>

<script>
import qs from 'qs'

import {
    examineDeclareList, // 申报和批量申报
    getDeclareList,
    getHistory, // 操作记录
    buildDoc, // 制作文件
    delDeclare, // 删除报关单
    examineOpea, // 复核or退回  auditFlag: 1 复核  0退回
    revertManifest,
    changeConfirmStatus
} from '@/api/declare'

import { changeData, getToken } from '@/libs/util.js'
import { downloadURL } from '@/config/downloadUrl.js'
import { declareStatus } from '@/libs/customsOptions.js'
import axios from '@/libs/api.request'

import DeclareTable from '../../components/declare-table'
import SearchExpand from '_c/search-expand'
import declareFailure from '../../components/declareFailure'
import declareSuccessModal from '../../components/declareSuccessModal'
import batchDownloadFailModal from '../../components/batchDownloadFailModal'
import printFile from '../../components/printFile'
import MoreSetting from '../js/more-setting-mixins'
import importModal from '../../components/importModal'

export default {
    inject: ['nextPageReload'],
    mixins: [MoreSetting],
    components: {
        importModal,
        DeclareTable,
        SearchExpand,
        declareFailure,
        declareSuccessModal,
        batchDownloadFailModal,
        printFile
    },
    data () {
        return {
            disFix: true,
            canEdit: true, // 编辑权限
            canView: true, // 查看权限

            addRoute: 'declareAddCK', // 新增路由名
            editRoute: 'declareEditCK', // 编辑路由名

            // 弹窗状态
            modalParams: {
                declareFailureParams: {},
                declareFailureShow: false,
                declareSucParams: {},
                declareSucShow: false
            },
            dataList: [], // 进口报关列表
            // 进口报关数据查询
            searchData: {
                declareNo: '', // 内部编码
                businessNo: '', // 订单编号
                businessStatus: '', // 状态
                businessType: 'CK', // 业务类型
                etpsInnerInvtNo: '',
                tradeCode: '',
                declDateStart: '',
                declDateEnd: '',
                containerNo: '',
                billNo: '',
                practicalTrainingId: '',
                pageNum: 1,
                pageSize: 10,
                total: 0
            },
            businessStatusArr: Object.freeze(declareStatus),

            delModalObj: {
                flag: '',
                title: '',
                dic: ''
            },
            delDataModel: false,

            // 制作文件
            makeFileModal: false,
            makeFileObj: {
                declareId: '',
                types: [],
                isCachet: ''
            },
            makeFilePercent: 0,

            // 申报信息
            declareResultModal: false, // 申报弹出框
            declareResultDataColumns: [
                // 申报失败表格
                {
                    title: '内部编号',
                    key: 'relNo'
                },
                {
                    title: '表名',
                    key: 'className'
                },
                {
                    title: '字段名',
                    key: 'fieldName'
                },
                {
                    title: '错误原因',
                    key: 'message'
                }
            ],
            declareResultDataList: [], // 申报失败列表

            // 报文记录
            operationRecordList: [],
            operationRecordModal: false,
            operationRecordListColumns: [
                {
                    title: '序列号',
                    type: 'index',
                    width: 80,
                    align: 'center'
                },
                {
                    title: '内部编号',
                    key: 'declareNo',
                    width: 220
                },
                {
                    title: '操作时间',
                    key: 'noticeDate',
                    width: 220,
                    render: (h, params) => {
                        return h('div', [
                            h(
                                'span',
                                {
                                    style: {
                                        display: 'inline-block',
                                        width: '100%',
                                        overflow: 'hidden',
                                        textOverflow: 'ellipsis',
                                        whiteSpace: 'nowrap'
                                    },
                                    domProps: {
                                        title: params.row.noticeDate
                                    }
                                },
                                params.row.noticeDate
                            )
                        ])
                    }
                },
                {
                    title: '报文信息',
                    key: 'receiptMessage',
                    render: (h, params) => {
                        return h('div', [
                            h(
                                'span',
                                {
                                    style: {
                                        display: 'inline-block',
                                        width: '100%',
                                        overflow: 'hidden',
                                        textOverflow: 'ellipsis',
                                        whiteSpace: 'nowrap'
                                    },
                                    domProps: {
                                        title: params.row.receiptMessage
                                    }
                                },
                                params.row.receiptMessage
                            )
                        ])
                    }
                }
            ],
            receiptData: {
                declareId: '',
                pageNum: 1,
                pageSize: 10
            },
            receiptTotal: 0,
            // 点击更多操作选中的报关单id
            currentDeclareId: '',

            // 进度条
            isHide: true
        }
    },
    created () {
        this.selection = [] // 复选框选中的数组
        this.searchData.practicalTrainingId = this.$route.params.trainingId
        this.queryDeclareList()
    },
    methods: {
        // 处理 搜索栏 创建时间 改变
        handleSearchDateChange (v) {
            this.searchData.declDateStart = v[0] || ''
            this.searchData.declDateEnd = v[1] || ''
        },
        // 搜索
        getList () {
            this.searchData.pageNum = 1
            this.queryDeclareList()
        },
        // 查询报关单数据
        queryDeclareList () {
            getDeclareList(this.searchData).then(res => {
                if (res.data.code === '0000') {
                    res.data.data.list.forEach(item => {
                        item.createTime = changeData(
                            new Date(item.createTime),
                            'yyyy-MM-dd hh:mm:ss'
                        )
                    })
                    this.dataList = res.data.data.list
                    this.searchData.total = res.data.data.total
                } else {
                    this.$Message.error(res.data.msg)
                }
            })
        },

        // 取消新建订单弹出框
        cancelDeclare () {
            this.declareResultModal = false
        },
        // 新建报关单
        addDeclaration () {
            this.nextPageReload()
            let show
            if (this.$route.name === 'declareEX' || this.$route.name === 'declareIM') {
                show = true
            } else {
                show = false
            }
            this.$router.push({
                name: this.addRoute,
                query: {
                    show
                }
            })
        },
        // 查看报关单
        handleView ({ declareId, declareNo }) {
            this.$router.push({
                name: this.editRoute,
                query: {
                    // 需要传 id 和 查看
                    declareNo,
                    declareId,
                    opea: 'show'
                }
            })
        },
        // 编辑报关单
        handleFix () {
            changeConfirmStatus({ declareId: this.selection[0].declareId, isConfirm: 0 }).then(res => {
                if (res.data.code != '0000') {
                    this.$Message.error(res.data.msg)
                    return
                }
                this.$router.push({
                    name: this.editRoute,
                    params: {
                        id: this.selection[0].declareId
                    },
                    query: {
                    // 需要传 id 和 修改
                        declareNo: this.selection[0].declareNo
                    }
                })
            })
        },
        handleBack () {
            revertManifest(this.selection[0].declareId).then(res => {
                if (res.data.code != '0000') {
                    this.$Message.error(res.data.msg)
                    return
                }
                this.$Message.success('撤销成功!')
                this.queryDeclareList()
            })
        },
        handleEdit ({ declareId, declareNo }) {
            this.$router.push({
                name: this.editRoute,
                params: {
                    id: declareId
                },
                query: {
                    // 需要传 id 和 修改
                    declareNo,
                    show: true
                }
            })
        },
        // 表格多选事件
        handleSelectionChange (list) {
            this.selection = list
            if (this.selection.length == 1 && this.selection[0].businessStatus == 0) {
                this.disFix = false
            } else {
                this.disFix = true
            }
        },

        // 关闭报文记录弹窗
        operationRecordCancel () {
            this.operationRecordList = []
            this.operationRecordModal = false
        },
        // 查询报文信息
        getReceiptInfo () {
            this.receiptData = {
                id: this.currentDeclareId,
                pageNum: 1,
                pageSize: 10
            }
            getHistory(this.receiptData).then(res => {
                if (res.data.code === '0000' == true) {
                    if (res.data.data.customsReceiptInfo.list.length) {
                        this.operationRecordList =
                            res.data.data.customsReceiptInfo.list
                        this.receiptTotal =
                            res.data.data.customsReceiptInfo.total
                        // 对时间进行过滤转换
                        for (let i in this.operationRecordList) {
                            this.operationRecordList[i].noticeDate = changeData(
                                new Date(
                                    this.operationRecordList[i].noticeDate
                                ),
                                'yyyy-MM-dd hh:mm:ss'
                            )
                        }
                    } else {
                        this.operationRecordList = []
                        this.$Message.success('无报文记录！')
                    }
                } else {
                    this.$Message.error(res.data.msg)
                }
            })
        },

        // 关闭制作文件弹窗
        makeFileCancel () {
            this.makeFileModal = false
        },
        // 制作文件
        makeFileOk () {
            if (this.makeFileObj.types.length == 0) {
                this.$Message.error('请选择要制作的文件')
            } else {
                this.isHide = false
                let data = {
                    param: {
                        declareId: this.currentDeclareId,
                        types: this.makeFileObj.types.join(','),
                        isCachet: this.makeFileObj.isCachet
                    },
                    Authorization: getToken()
                }
                buildDoc(data).then(res => {
                    if (res.data.code === '0000') {
                        let param = encodeURI(JSON.stringify(data.param))
                        let url = '/ui/dataFileDownload/exportDeclareXls'
                        window.open(
                            `${downloadURL}${url}?param=${param}&Authorization=${data.Authorization}`
                        )
                        this.makeFileModal = false
                        this.isHide = true
                    } else {
                        this.$Message.error(res.data.msg)
                    }
                })
            }
        },

        // 更多操作弹窗
        openMoreModal ($event, row) {
            this.currentDeclareId = row.declareId
            this.isConfirm = row.isConfirm
            const { x, y, offsetX, offsetY } = $event
            this.showMoreBox(x - offsetX - 70, y - offsetY + 20)
        },
        // 统一处理更多操作弹窗的事件
        handleMore (e) {
            let handleType = e.target.innerHTML
            switch (handleType) {
                case '导入单一窗口':
                    /* if (!this.isConfirm) {
                        this.$Message.warning(
                            '报关单未确认，不能导入单一窗口!'
                        )
                        return false
                    } */
                    let data = {
                        declareIds: this.currentDeclareId
                    }
                    this.declareCommonFn(data)
                    break
                case '删除':
                    this.delModalObj = {
                        flag: 'SC',
                        title: '删除',
                        dic: '删除数据无法恢复,是否确认删除?'
                    }
                    this.delDataModel = true
                    break
                case '制作文件':
                    /* if (!this.isConfirm) {
                        this.$Message.warning('报关单未确认，不能制作文件!')
                        return false
                    } */
                    this.makeFileModal = true
                    break
                case '打印文件':
                    this.$refs.printFileRef.init(this.currentDeclareId)
                    break
                case '报文记录':
                    this.operationRecordModal = true
                    this.getReceiptInfo()
            }
        },

        // 关闭弹窗
        delCancel () {
            this.delDataModel = false
        },
        // 弹窗 删除 复合or退回
        delOk (id) {
            let data = {
                declareIds: id
            }
            let fn = delDeclare
            if (this.delModalObj.flag == 'FH') {
                data.auditFlag = '1'
                fn = examineOpea
            } else if (this.delModalObj.flag == 'HT') {
                data.auditFlag = '0'
                fn = examineOpea
            }
            fn(data).then(res => {
                this.delDataModel = false
                if (res.data.code == '0000') {
                    this.$Message.success(res.data.msg)
                    this.queryDeclareList()
                } else {
                    this.$Message.error(res.data.msg)
                }
            })
        },

        // 报表导出
        reportExport () {
            let data = {
                Authorization: getToken(),
                declareNo: this.searchData.declareNo,
                businessNo: this.searchData.businessNo,
                businessStatus: this.searchData.businessStatus,
                businessType: this.searchData.businessType,
                declareIds: ''
            }
            data.declareIds = this.selection
                .map(item => item.declareId)
                .join(',')
            let params = Object.keys(data)
                .map(k => `${k}=${data[k]}`)
                .join('&')
            let url =
                downloadURL +
                '/ui/dataFileDownload/downLoadDeclareList?' +
                params
            console.log(url)
            window.open(url)
        },

        // 批量下载
        batchDownload () {
            if (this.selection.length === 0) {
                this.$Message.warning('请勾选报关单信息！')
                return false
            }
            axios
                .request({
                    method: 'get',
                    url: '/ui/dataFileDownload/downloadDeclareFiles',
                    params: {
                        param: {
                            declareIds: this.selection
                                .map(item => item.declareId)
                                .join(',')
                        },
                        Authorization: getToken()
                    }
                })
                .then(res => {
                    if (res.constructor === Object && res.data.data) {
                        // 批量下载随附单据错误
                        console.log(res.data.data)
                        this.$refs.batchDownloadFailModalRef.init(
                            res.data.data
                        )
                    } else {
                        let newUrl =
                            downloadURL +
                            '/ui/dataFileDownload/downloadDeclareFiles?param=' +
                            params +
                            '&Authorization=' +
                            data.Authorization
                        window.open(newUrl)
                        this.selection = []
                    }
                })
        },

        // 批量导入单一窗口
        sendDeclare () {
            if (this.selection.length === 0) {
                this.$Message.warning('请勾选报关单信息！')
                return false
            }
            let arr = this.selection.filter(item => !item.isConfirm)
            if (arr.length > 0) {
                let errMsg = arr.map(item => item.declareNo).join(',')
                this.$Message.warning({
                    content: '报关单' + errMsg + '未确认，不能申报！',
                    duration: 5,
                    closable: true
                })
                return false
            }
            let obj = {
                declareIds: this.selection.map(item => item.declareId).join(',')
            }
            this.declareCommonFn(obj) // 申报公共方法
        },

        // 申报公共方法
        declareCommonFn (obj) {
            examineDeclareList(qs.stringify(obj)).then(res => {
                if (res.data.code === '0000') {
                    // 判断失败数量是否为0, 0带表申报成功
                    if (res.data.data.failNum === 0) {
                        this.modalParams.declareSucParams = {
                            sendAllText: '发送成功！'
                        }
                        this.modalParams.declareSucShow = true
                    } else {
                        // 有错误的报关单则显示错误信息
                        const { failDeclareNo, resultList } = res.data.data
                        this.$Modal.error({
                            title: `${failDeclareNo} 导入失败`,
                            width: '500px',
                            render (h) {
                                return h('Table', {
                                    style: {
                                        width: '100%'
                                    },
                                    props: {
                                        height: '250px',
                                        columns: [
                                            {
                                                title: '内部编号',
                                                key: 'retCode',
                                                width: 160,
                                                align: 'center'
                                            },
                                            {
                                                title: '错误信息',
                                                key: 'retMsg',
                                                align: 'center',
                                                tooltip: true
                                            }
                                        ],
                                        data: resultList || []
                                    }
                                })
                            }
                        })
                    }
                } else {
                    if (res.data.code == '1010') {
                        this.$refs.perfectCompanyInfoModalRef.init() // 导入随附单据，需要用到IC卡号，请补全以下信息
                    } else {
                        let data = res.data.data
                        this.openDeclareFailureModal({ data, obj })
                    }
                }
            })
        },

        // 打开申报失败弹窗
        openDeclareFailureModal (params) {
            this.modalParams.declareFailureParams = params
            this.modalParams.declareFailureShow = true
        },
        // 导入功能
        importModel () {
            this.$refs.importModalRef.init(this.searchData.businessType, this.searchData.practicalTrainingId)
        }
    } // methods end
}
</script>
<style lang="less" scoped>
.content-footer {
    margin-top: 14px;
    text-align: right;
}
.declare-list-content {
    position: relative;
    .more-box {
        position: fixed;
        display: none;
        z-index: 99999;
        width: 100px;
        height: 155px;
        padding: 10px 0;
        background-color: #fff;
        border-radius: 4px;
        box-shadow: 0 1px 6px rgba(0,0,0,.2);
        box-sizing: border-box;

        a {
            display: block;
            padding: 3px 0 3px 15px;
            font-size: 14px;
            color: #383a4a;

            &:hover {
                background-color: #E8F1FE
            }
        }
    }
}
</style>
